package des.wangku.operate.standard.task;

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.Proxy.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 系统级配置信息的提取对像
 * @author Sunjian
 * @version 1.0
 * @since jdk1.8
 */
public interface InterfacePropertiesObject extends InterfaceProperties {
	static Logger logger = LoggerFactory.getLogger(InterfacePropertiesObject.class);

	/**
	 * 从配置读取以关键以前提的代理<br>
	 * 例:key="Proxy_0_"<br>
	 * 读取:Proxy_0_Type,Proxy_0_Host,Proxy_0_Port,Proxy_0_User,Proxy_0_Pass
	 * @param key String
	 * @return Proxy
	 */
	public default Proxy getProPProxy(String key) {
		String cType = this.getProPropValue(key + "Type", "").trim().toLowerCase();
		String host = this.getProPropValue(key + "Host", "").trim();
		int port = this.getProPropInteger(key + "Port", 0);
		String user = this.getProPropValue(key + "User", "").trim();
		String pass = this.getProPropValue(key + "Pass", "").trim();
		if (host == null || host.length() == 0) return null;
		if (port <= 0) return null;
		Type type=Type.DIRECT;
		if("socks".equals(cType)) {
			type=Type.SOCKS;
		}
		if("http".equals(cType)||"https".equals(cType)) {
			type=Type.HTTP;
		}
		if (user.length() > 0 && pass.length() > 0) {
			Authenticator.setDefault(new Authenticator() {
				public PasswordAuthentication getPasswordAuthentication(){
					return new PasswordAuthentication(user, pass.toCharArray());
				}
			});
		}
		Proxy proxy = new Proxy(type, new InetSocketAddress(host, port));
		return proxy;
	}

}
